package com.guotd.jspwork2.controller;

import com.guotd.jspwork2.utils.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import static com.guotd.jspwork2.utils.JDBCUtil.getConnection;

@WebServlet("/saveKind")
public class saveKindServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String kindName = request.getParameter("kind");
        String desc = request.getParameter("desc");
       /* try (Connection con = getConnection();
             PreparedStatement pstmt = con.prepareStatement("insert into kind(kind,desc) values(?,?)");
            ) {
            pstmt.setString(1, kindName);
            pstmt.setString(2, desc);
            int row= pstmt.executeUpdate();
            if (row > 0) {
                request.getSession().setAttribute("kind_msg", "保存成功");
                response.sendRedirect("getAllKinds");
            }else {
                request.setAttribute("kind_msg","保存失败");
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }*/
        String sql = "insert into kind(kind,desc) values(?,?)";
        String []args = {kindName, desc};
        int row= JDBCUtil.update(sql, args);
        if (row > 0) {
            request.getSession().setAttribute("kind_msg", "保存成功");
            response.sendRedirect("getAllKinds");
        }else {
            request.setAttribute("kind_msg","保存失败");
        }
    }
}